<template>
  <div class="send-medici-container">
    <!-- 顶部区域 -->
    <div class="send-medici-header">
		<i class="el-icon-zy" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #00aa00;color: #fff;"></i>
		<h4 style="margin-left: 12px;">中药房门诊发药</h4>
    </div>
    
    <!-- 主体区域 -->
    <div class="send-medici-main">
      <!-- 左侧区域 (30%宽度) -->
      <div class="send-medici-left">
        <!-- 左侧上部表单 -->
        <div class="left-form">
          <el-form label-position="left" size="small">
            <el-form-item label="药房名称">
              <el-select v-model="form.pharmacyName" placeholder="请选择药房">
                <el-option label="中药房" value="中药房"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="发药窗口">
              <el-select v-model="form.dispensingWindow" placeholder="请选择窗口">
                <el-option label="门诊1号窗口" value="门诊1号窗口"></el-option>
                <el-option label="门诊2号窗口" value="门诊2号窗口"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="窗口状态">
              <el-radio-group v-model="form.windowStatus">
                <el-radio label="启用">启用</el-radio>
                <el-radio label="暂停使用">暂停使用</el-radio>
              </el-radio-group>
            </el-form-item>
                  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">健康ID</span>
				  <el-input v-model="form.healthId" placeholder="请输入健康ID"></el-input>
				</div>
			  </el-form-item>
			  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">处方查找</span>
				  <el-input v-model="form.prescriptionSearch" placeholder="处方编号"></el-input>
				</div>
			  </el-form-item>
			  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">患者姓名</span>
					<el-input v-model="form.name" placeholder="姓名/拼音简码"></el-input>
					<el-button type="primary" size="small" style="margin-left: 10px;" :loading="loading" @click="getUserInfo">刷新</el-button>
				</div>
			  </el-form-item>
			  
			  <el-form-item>
				<div class="form-item-row">
				  <span class="form-label">刷新时长</span>
				  <el-input v-model="form.refreshTime" placeholder="秒" style="width: 60px;"></el-input>
				  <el-checkbox v-model="form.showBatch" style="margin-left: 10px;">显示药品批次</el-checkbox>
				</div>
			  </el-form-item>
			</el-form>
        </div>
        
        <!-- 左侧下部表格 -->
        <div class="left-table">
          <el-table
            :data="leftTableData"
            border
            style="width: 100%"
            :height="leftTableHeight"
			@row-dblclick="getDataValue"
            size="small">
            <el-table-column type="index" label="行号" width="48"></el-table-column>
            <el-table-column prop="name" label="病人姓名" width="88"></el-table-column>
            <el-table-column prop="age" label="年龄" width="60"></el-table-column>
			<el-table-column prop="sex" sortable label="性别" width="80">
			  <template slot-scope="scope">
			    <span>
			      <i :class="scope.row.sex === 1? 'el-icon-male' : 'el-icon-female'" 
			          :style="{color: scope.row.sex === 1 ? '#409EFF' : '#F56C6C'}"></i>
			      {{ scope.row.sex === 1 ? '男' : '女' }}
			    </span>
			  </template>
			</el-table-column>
			<el-table-column prop="state" label="状态">
				<template slot-scope="{ row }">
					<!-- 根据state显示不同的图标 -->
					<div class="stateValue" style="border-radius: 4px;background-color: #e2fff6;text-align: center;color: #004a00;">
						<i :class="statusIconMap[row.state]" :style="{ color: statusColorMap[row.state] }"></i>
						<span>{{ statusMap[row.state] || '未知状态' }}</span>
					</div>
				</template>
			</el-table-column>
<!--        <el-table-column prop="rxName" label="处方类型" width="100"></el-table-column>
            <el-table-column prop="rxNo" label="处方编号" width="120"></el-table-column>
			<el-table-column prop="saleAmt" label="处方金额" width="80"></el-table-column>
			<el-table-column prop="deptName" label="处方科室" width="120"></el-table-column>
			<el-table-column prop="fullName" label="处方医生" width="120"></el-table-column>
			<el-table-column prop="icdName" label="中医诊断" width="120"></el-table-column> -->
            <el-table-column prop="patientId" label="健康id" width="80"></el-table-column>
            <el-table-column prop="state" label="状态" width="100"></el-table-column>
            <el-table-column prop="remark" label="备注" width="80"></el-table-column>
          </el-table>
        </div>
      </div>
      
      <!-- 右侧区域 (70%宽度) -->
      <div class="send-medici-right">
        <!-- 右侧上部表单 -->
        <div class="right-form">
          <el-form :inline="true" size="small">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="处方编号">
                  <el-input v-model="rightForm.rxNo" placeholder="请输入处方编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病员姓名">
                  <el-input v-model="rightForm.name" placeholder="请输入病员姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="病人身份证">
                  <el-input v-model="rightForm.cardId" placeholder="请输入病人身份证"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="性别">
					<el-select v-model="rightForm.sex" placeholder="请选择性别">
					  <el-option v-for="item in sexOptions" :key="item.id" :label="item.label" :value="item.id">
					  <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
					</el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="年龄">
                  <el-input v-model="rightForm.age" placeholder="请输入年龄"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="健康id">
                  <el-input v-model="rightForm.patientId" placeholder="健康id"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处方科室">
                  <el-input v-model="rightForm.deptName" placeholder="请输入处方科室"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处方医生">
                  <el-input v-model="rightForm.fullName" placeholder="请输入处方医生"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="处方金额">
                  <el-input v-model="rightForm.saleAmt" placeholder="请输入处方金额"></el-input>
                </el-form-item>
              </el-col>
             
<!--              <el-col :span="6">
                <el-form-item label="皮试处方">
                  <el-select v-model="rightForm.sex" placeholder="皮试处方">
                    <el-option v-for="item in YNOption" :key="item.id" :label="item.label" :value="item.id">
                    <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
			  <el-col :span="6">
			    <el-form-item label="用药频率">
			      <el-input v-model="rightForm.usedFrqu" placeholder=""></el-input>
			    </el-form-item>
			  </el-col>
              <el-col :span="6">
                <el-form-item label="用法">
                  <el-input v-model="rightForm.tcmWayName" placeholder=""></el-input>
                </el-form-item>
              </el-col>
			  <el-col :span="6">
			    <el-form-item label="给药方式">
			      <el-input v-model="rightForm.medcWay" placeholder=""></el-input>
			    </el-form-item>
			  </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item label="中医诊断">
                  <el-input v-model="rightForm.icdName" placeholder="请输入中医诊断"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="备注">
                  <el-input v-model="rightForm.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
              </el-col>
              
            </el-row>
            
          </el-form>
        </div>

          <!-- 右侧下部表格 -->
            <div class="right-table">
              <el-table
                ref="rightTable"
                :data="rightTableData"
                border
                style="width: 100%"
                :height="rightTableHeight"
                size="small"
                show-summary
                :summary-method="getSummaries">
                <el-table-column type="index" label="行号" width="60"></el-table-column>
                <el-table-column prop="name" label="药品名称" width="128"></el-table-column>
				<el-table-column prop="code" label="药品编码" width="128"></el-table-column>
                <el-table-column prop="drugSpec" label="药品规格" width="120"></el-table-column>
                <!-- <el-table-column prop="purcType" label="库存类型" width="100"></el-table-column> -->
                <el-table-column prop="cnt" label="数量" width="80"></el-table-column>
                <el-table-column prop="unt" label="单位" width="60"></el-table-column>
                <el-table-column prop="tcmWayName" label="用法" width="120"></el-table-column>
                <el-table-column prop="usedFrquName" label="频次" width="100"></el-table-column>
                <!-- <el-table-column prop="prdDays" label="天数" width="60"></el-table-column> -->
                <el-table-column prop="purcPric" label="单价" width="80"></el-table-column>
                <el-table-column prop="saleAmt" label="金额" width="80"></el-table-column>
                <el-table-column prop="manuLotnum" label="批号" width="100"></el-table-column>
                <el-table-column prop="expyDate" label="有效期" width="120"></el-table-column>
                <el-table-column prop="prodentpName" label="生产厂家" width="150"></el-table-column>
              </el-table>
            </div>
 
      </div>
    </div>
    
    <!-- 底部区域 (100%宽度) -->
    <!-- 底部按钮区域 -->
    <div class="send-medici-bottom">
      <div class="bottom-left">
        <el-button :loading="buttonLoading.print" type="warning" size="small">打印</el-button>
        <el-checkbox :disabled="buttonLoading.print" v-model="closeAfterPrint" style="margin-left: 10px;">自动打印</el-checkbox>
      </div>
      <div class="bottom-right">
        <el-button :loading="buttonLoading.callPatient" type="primary" size="small">呼叫患者</el-button>
        <el-button :loading="buttonLoading.skipNumber" type="primary" size="small">一键过号</el-button>
        <el-button :loading="buttonLoading.refund" type="primary" size="small">许可退费</el-button>
        <el-button :loading="buttonLoading.printPrescription" type="primary" size="small">打印处方</el-button>
        <el-button :loading="buttonLoading.batchDispense" type="primary" size="small">批量发药</el-button>
        <el-button :loading="buttonLoading.sendMedic" type="success" size="small" @click="sendMedic">发药</el-button>
        <el-button :loading="buttonLoading.close" type="danger" size="small">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
// 接口
import { tcmDisselectPatientInfo,tcmFySave } from "@/api/MedicenHouse/traMediciGive.js";
// import { tcmDisselectPatientInfo,tcmFySave } from "@/api/MedicenHouse/WesternGive.js";

export default {
  name: 'SendMedici',
  inject: ['reload'], // 无痕刷新
  data() {
    return {
		searchedValue:'', // 患者姓名
		patientId:'', // 健康ID
		rxNoValue:'', // 处方编码
		
		// blean
		loading:false,
		sexOptions:[{id:1,label:'男',value:'男'},{id:2,label:'女',value:'女'}],
		YNOption:[{id:0,label:'否'},{id:1,label:'是'}],//库房
		timer: null, // 计时器
		buttonLoading: { // 各按钮的加载状态
		  print: false,
		  callPatient: false,
		  skipNumber: false,
		  refund: false,
		  printPrescription: false,
		  batchDispense: false,
		  sendMedic: false,
		  close: false
		},
      form: {
        pharmacyName: '中药房',
        dispensingWindow: '1号窗口',
        windowStatus: '启用',
        healthId: '',
        prescriptionSearch: '',
        name: '',
        refreshTime: '10',
        showBatch: true
      },
      rightForm: {
			"age": 0,
			"agnterCretno": "",
			"agnterName": "",
			"cardId": "",
			"deptName": "",
			"fullName": "",
			"icdName": "",
			"id": 0,
			"name": "",
			"patientId": 0,
			"remark": "",
			"rxName": "",
			"rxNo": 0,
			"saleAmt": 0,
			"sex": 0,
			"skintstRx": 0,
			"state": 0,
			"voList": [
				{
					"cnt": 0,
					"dosform": "",
					"drugId": 0,
					"drugName": "",
					"drugSpec": "",
					"dugPurcId": 0,
					"expyDate": "",
					"frequency": "",
					"manuLotnum": "",
					"maxPurcPric": 0,
					"maxSalePric": 0,
					"minPurcPric": 0,
					"minSalePric": 0,
					"pacCnt": 0,
					"prdDays": 0,
					"prodentpName": "",
					"prodentpNameId": 0,
					"purcAmt": 0,
					"purcPric": 0,
					"purcType": "",
					"rdDetailsId": 0,
					"rxId": 0,
					"saleAmt": 0,
					"salePric": 0,
					"saleUnt": 0,
					"supplyCandidateId": 0,
					"unt": "",
					"usageName": ""
				}
			]
      },
      leftTableData: [
        {
          rowNumber: 1,
          patientName: '张三',
          prescriptionNumber: 'P20230001',
          patientType: '门诊',
          age: 35,
          callCount: 2,
          callStatus: '已完成',
          printCount: 1
        },
        {
          rowNumber: 2,
          patientName: '李四',
          prescriptionNumber: 'P20230002',
          patientType: '住院',
          age: 42,
          callCount: 1,
          callStatus: '待处理',
          printCount: 0
        }
      ],
	  detailsVo: [],
      rightTableData: [],
	  // props
	  statusMap: {
	  	0: '草稿',
	  	1: '已收费',
	  	2: '已配药',
	  	3: '已发药',
	  	4: '已退药'
	  },
	  statusIconMap: {
	  	0: 'el-icon-document',
	  	1: 'el-icon-top-left',
	  	2: 'el-icon-check',
	  	3: 'el-icon-bottom-right',
	  	4: 'el-icon-document-checked',
	  },
	  statusColorMap: {
	  	0: '#909399',
	  	1: '#67C23A',
	  	2: '#409EFF',
	  	3: '#E6A23C',
	  	4: '#F56C6C',
	  },
      closeAfterPrint: true,
      leftTableHeight: '100%',
      rightTableHeight: '100%'
    }
  },
  mounted() {
	this.loadData();
    this.calculateTableHeights();
    window.addEventListener('resize', this.calculateTableHeights);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeights);
  },
  methods: {
	async loadData(){
		this.loading = true;
		let res = await tcmDisselectPatientInfo({
			name:this.searchedValue,
			patientId:this.patientId,
			rxNo:this.rxNoValue,
		});
		if(res.code === 200){
			this.leftTableData = res.data
			console.log(this.leftTableData,'leftTableDataleftTableData');
			this.totalSize = res.data.totalSize
			this.loading = false;
		}else{
			// this.$message({ type: 'error', message: res.message });
			this.tableData = [];
			this.loading = false;
		}
	  },
	  // 刷新按钮查询条件
	  getUserInfo(){
		this.searchedValue = this.form.name; // 患者姓名
		this.patientId = this.form.healthId; // 健康id
		this.rxNoValue = this.form.rxNoValue; // 处方查找
		this.loadData();
	  },

	  // 双击事件
	  getDataValue(row) {
	    console.log(row);
	    this.rightForm = row;
	    
	    // 确保金额和数量是数字类型
	    this.rightTableData = row.voList.map(item => ({
	      ...item,
	      purcAmt: Number(item.purcAmt) || 0,
	      cnt: Number(item.cnt) || 0
	    }));
	    
	    // 强制重新计算合计行
	    this.$nextTick(() => {
	      this.$refs.rightTable?.doLayout();
	    });
	  },
	  setAllButtonsLoading(isLoading) {
	      this.loading = isLoading;
	      // 设置所有按钮的加载状态
	      for (let key in this.buttonLoading) {
	        this.buttonLoading[key] = isLoading;
	      }
	    },
	  // 发药按钮
	  async sendMedic() {
	    // 清除之前的定时器
	    if (this.timer) {
	      clearTimeout(this.timer);
	    }
	    
	    console.log(this.rightTableData, '发药数据');
	    this.detailsVo = this.rightTableData;
	    
	    // 设置所有按钮为加载状态
	    this.setAllButtonsLoading(true);
	    
	    try {
	      let res = await tcmFySave(this.detailsVo);
	      
	      if (res.code === 200) {
	        this.$message({ type: 'success', message: res.message });
	        
	        // 设置3秒后自动刷新
	        this.timer = setTimeout(() => {
	          this.reload();
	        }, 3000);
	        
	      } else {
	        this.$message.error(res.message);
	      }
	    } catch (error) {
	      console.error('发药出错:', error);
	      this.$message.error('发药失败');
	    } finally {
	      // 无论成功失败，都关闭加载状态
	      this.setAllButtonsLoading(false);
	    }
	  },
	
	// 添加合计行计算方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        
        // 定义需要合计的列
        const sumColumns = ['cnt', 'purcAmt', 'saleAmt', 'purcPric', 'salePric'];
        
        if (sumColumns.includes(column.property)) {
          const values = data.map(item => {
            // 确保数据是数字类型
            const value = Number(item[column.property]);
            return isNaN(value) ? 0 : value;
          });
          
          // 计算合计值
          const sum = values.reduce((prev, curr) => prev + curr, 0);
          
          // 金额保留2位小数
          sums[index] = ['purcAmt', 'saleAmt', 'purcPric', 'salePric'].includes(column.property) 
            ? sum.toFixed(2) 
            : sum;
        } else {
          sums[index] = '';
        }
      });
    
      return sums;
    },
    calculateTableHeights() {
      // 计算左侧表格高度
      const leftFormHeight = document.querySelector('.left-form')?.offsetHeight || 300;
      const leftTableHeight = window.innerHeight - 50 - 50 - leftFormHeight - 20; // 减去header、bottom和form高度以及padding
      this.leftTableHeight = Math.max(200, leftTableHeight) + 'px';
      
      // 计算右侧表格高度
      const rightFormHeight = document.querySelector('.right-form')?.offsetHeight || 300;
      const rightTableHeight = window.innerHeight - 50 - 50 - rightFormHeight - 20; // 减去header、bottom和form高度以及padding
      this.rightTableHeight = Math.max(200, rightTableHeight) + 'px';
    }
  }
}
</script>

<style lang="less" scoped>
	/* 添加合计行样式 */
	/deep/ .el-table__footer-wrapper .el-table__footer .cell {
	  font-weight: bold;
	  color: #aa0000;
	}
	
.send-medici-container {
  width: 100%;
  height: 90vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  overflow: hidden;
  
  .send-medici-header {
    height: 50px;
    background-color: #409EFF;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 20px;
    flex-shrink: 0;
    
    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: normal;
    }
  }
  
  .send-medici-main {
    flex: 1;
    display: flex;
    overflow: hidden;
    
    .send-medici-left {
      width: 20%;
      height: 100%;
      display: flex;
      flex-direction: column;
      border-right: 1px solid #e6e6e6;
      background-color: white;
      overflow: hidden;
      
      /* 新增样式 */
      .left-form {
        padding: 10px;
        border-bottom: 1px solid #e6e6e6;
        overflow-y: auto;
        flex-shrink: 0;
        
        .el-form-item {
          margin-bottom: 10px;
          
          .form-item-row {
            display: flex;
            align-items: left;
            width: 100%;
            
            .form-label {
              width: 58px;
              text-align: left;
              padding-right: 10px;
              color: #606266;
            }
            
            .el-select, .el-input {
              flex: 1;
              min-width: 88px;
            }
            
          }
        }
      }
      
      .left-table {
        flex: 1;
        overflow: auto;
        padding: 10px;
      }
    }
    
    .send-medici-right {
      width: 80%;
      height: 100%;
      display: flex;
      flex-direction: column;
      background-color: white;
      overflow: hidden;
      
      .right-form {
        padding: 10px;
        border-bottom: 1px solid #e6e6e6;
        overflow-y: auto;
        flex-shrink: 0;
        
        .el-form-item {
          margin-bottom: 10px;
          width: 100%;
        }
        
        .el-row {
          margin-bottom: 10px;
        }
      }
      
      .right-table {
        flex: 1;
        overflow: auto;
        padding: 10px;
      }
    }
  }
  
  .send-medici-bottom {
    height: 50px;
    background-color: white;
    border-top: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    flex-shrink: 0;
    
    .bottom-left, .bottom-right {
      display: flex;
      align-items: center;
    }
  }
}
</style>